#!/usr/bin/python
# -*- coding: utf-8 -*-

# Copyright (c) 2011
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation

# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
# Author: Jesus Carrero <j.o.carrero@gmail.com>
# Mountain View, CA
#

from scipy.linalg import norm
from scipy import array

from utils.MainLog import runGlobalLogger
from utils.FemBases import LagrangeP1, LagrangeP2

import models.NumericalOptionGBM as nOp
from models.AnalyticalFormulas import vanillaCallPrice

from solvers.EuropeanTimeStepper import EuropeanTimeStepper

import logging
import unittest


class AccurancyTestSuite(unittest.TestCase):

    def setUp(self):
        """ I don't know how to avoid this """

        self.m_r = float(0.05)
        self.m_q = 0.0
        self.m_sigma = float(0.2)
        self.m_exp_time = float(1.0)
        self.m_S0 = 40
        self.m_K = 50

        (self.m_ntimestep_p1, self.m_nsegs_p1) = (None, None)
        (self.m_ntime_step_p2, self.m_nsegs_p2) = (None, None)

        (self.m_Smin, self.m_Smax) = (10, 130)

        self.m_keep_hist = False
        self.m_error_tol = 0.12

        self.m_lagrangeP1 = LagrangeP1()
        self.m_lagrangeP2 = LagrangeP2()

    def _init_engine(self, option_style, scheme_type):
        """ instantiate all the objects neede for the test case. """

        nsegs = {'P1': self.m_nsegs_p1,
                 'P2': self.m_nsegs_p2}[scheme_type]

        ntime_steps = {'P1': self.m_ntimestep_p1,
                       'P2': self.m_ntime_step_p2}[scheme_type]

        if 'E' == option_style:
            self.euOpt = nOp.NumericalOptionGBM('E', self.m_exp_time,
                    self.m_S0, self.m_K, ntime_steps, nsegs, self.m_Smin,
                    self.m_Smax)
        elif 'A' == option_style:
            self.euOpt = nOp.NumericalOptionGBM('A', self.m_exp_time,
                    self.m_S0, self.m_K, ntime_steps, nsegs, self.m_Smin,
                    self.m_Smax)
        else:
            assert False

        is_real = True
        self.euOpt.set_option_cos(self.m_sigma, self.m_q, self.m_r, is_real, \
                is_real, is_real)

        if 'P1' == scheme_type:
            self.euOpt.set_shape_functions(self.m_lagrangeP1)
        elif 'P2' == scheme_type:
            self.euOpt.set_shape_functions(self.m_lagrangeP2)


class PlainVanillaEuroCall(AccurancyTestSuite):
    """ under GBM model. """

    def runTest(self):
        """ overload base class. """

        print ' '
        self.m_ntimestep_p1 = self.m_ntime_step_p2 = 32
        self.m_sigma = 0.31
        rOfConvLog = logging.getLogger('RateOfConvergence')
        rOfConvLog.info('   (n time steps = '
                        + str(self.m_ntimestep_p1) + ')  ' + '(vol = '
                        + str(self.m_sigma ** 2) + ')  ' + '(r = '
                        + str(self.m_r) + ')')
        rOfConvLog.info('    n          error        ratio')

        error_l2 = []
        nsegs = array([int(2 ** k) for k in range(2, 9)], 'int')

        time_stepper = EuropeanTimeStepper()
        time_stepper.set_number_steps(self.m_ntime_step_p2)
        time_stepper.set_dolog(False)
        time_stepper.set_time2simulate(self.m_exp_time)
        time_stepper.set_keep_hist(self.m_keep_hist)

        for scheme_type in ['P1', 'P2']:
            rOfConvLog.info('         Lagrange ' + scheme_type)
            prev = 0.0
            for k in nsegs:
                self.m_nsegs_p1 = self.m_nsegs_p2 = k

                self._init_engine('E', scheme_type)
                self.euOpt.set_dolog(False)
                self.euOpt.set_time_stepper(time_stepper)

                (S, CallV) = self.euOpt.price_call()

                call_vanella_exact = vanillaCallPrice(S, self.m_K,
                        self.m_r, self.m_sigma, self.m_exp_time)
                call_vanella_exact[call_vanella_exact < 1.0e-6] = 0.0
                error_l2 = norm(CallV - call_vanella_exact)
                rOfConvLog.info(' %5d    %12.11f    %12.11f' % (k,
                                error_l2, prev / error_l2))
                prev = error_l2
            rOfConvLog.info('')


def mySuite():
    """ all test cases in the suite. """

    suite = unittest.TestSuite()
    suite.addTest(PlainVanillaEuroCall())
    return suite


if __name__ == '__main__':

    runGlobalLogger()
    runner = unittest.TextTestRunner(verbosity=2)
    result = runner.run(mySuite())

